package ;
import flixel.FlxCamera;
import flixel.FlxSprite;
import flixel.group.FlxGroup;
import openfl.Assets;
import flixel.addons.tile.FlxTilemapExt;
import haxe.xml.Fast;
import haxe.xml.Parser;
import flixel.FlxG;
/**
 * ...
 * @author Federico Donnet
 */
class PatronTileMap extends FlxTilemapExt
{

	//--------------------------------------------------------------------------------//
	//---*Atributos:
	//--------------------------------------------------------------------------------//
	private var xml:Xml;
	private var fastXml:Fast;
	private var mapElement: Fast		=	null;

	public	var	tileWidth: Int;
	public	var	tileHeight: Int;
	
	public	var	widthInPixels:Int;
	public	var	heightInPixels:Int;
	
	
	//---*Data del arreglo de tiles de este tileMap:
	public	var	tilemapData:Dynamic		=	null;
	//---*Data del arreglo de items de este tileMap:
	public	var	itemsData:Dynamic		=	null;
	//---*Referencia al level que contiene este patron:
	public	var	level: Level				=	null;	
	//---*Lista de items propios de este patron:
	public	var	itemList:Array<Fast>	=	null;	
	//---*Indica si se fue de camera (SOLO si ya paso y su posicion en X menos el ancho es menor a 0):
	public	var	isOut:Bool				=	false;
	//---*Indica su pocision en la fila:
	public	var	activeIndex:Int			=	0;
	//---*String que almacena el source:
	public	var	sourceTMX:String		=	"";
	//---*Array de posibles conexiones ("Patrones Vecinos"):
	public	var	conexiones:Array<Int>	=	null;
	//--------------------------------------------------------------------------------//
	//---*Metodos:
	//--------------------------------------------------------------------------------//
	
	
	public function new(TMXfile:Dynamic) 
	{		
		super();
		
		this.conexiones					=	new Array<Int>();
		this.sourceTMX					=	TMXfile;
		//---*Auxiliares para leer y almacenar datos de interes que luego ayudaran a armar el tileMap
		//---*Leen el archivo "TMX":
		var str:String = "";
		var widthInTiles:Int;
		var heightInTiles:Int;
		if (Std.is(TMXfile, Class)) // passed embedded resource?
		{
			str = Type.createInstance(TMXfile, []);
		}
		else if (Std.is(TMXfile, String))  // passed path to resource?
		{
			str = Assets.getText(TMXfile);
		}
		this.xml = Parser.parse(str);
		this.fastXml = new Fast(xml);
		if (!fastXml.hasNode.map)
			throw "ERROR: Couldn't find map node in tilemap";
		this.mapElement = fastXml.node.map;
		if (!mapElement.has.width)
			throw "ERROR: Couldn't read width attribute from tilemap";
		widthInTiles = Std.parseInt(mapElement.att.width);
		if (!mapElement.has.height)
			throw "ERROR: Couldn't read height attribute from tilemap";
		heightInTiles = Std.parseInt(mapElement.att.height);
		if (!mapElement.has.tilewidth)
			throw "ERROR: Couldn't read tilewidth attribute from tilemap";
		this.tileWidth = Std.parseInt(mapElement.att.tilewidth);
		if (!mapElement.has.tileheight)
			throw "ERROR: Couldn't read tileheight attribute from tilemap";
		this.tileHeight = Std.parseInt(mapElement.att.tileheight);
		
		this.widthInPixels			=	widthInTiles * this.tileWidth;
		this.heightInPixels			=	heightInTiles * this.tileHeight;
		
		//---*Obtenemos la linea con las conexiones:
		var conectionsData:Dynamic 	=	Utils.GetConectionsData(Utils.LEVELMANAGERTMX, Utils.LEVEL_01_NAME, TMXfile);
		//---*Almacenamos cada index de la linea en el array (conections):
		if (conectionsData != null)
		{
			GenerateConections(conectionsData);
		}
		
	}

	function	GenerateConections(conectionsData:Dynamic):Void
	{
		var aux:String = conectionsData;
		var list:Array<String> = aux.split(",");
		var index:Int = 0;
		
		while (index < list.length)
		{
			this.conexiones.push(Std.parseInt(list[index]));
			trace(this.conexiones[index]);
			index += 1;
		}
		
	}
	
	public	function	GenerateTileMap(tileGraphic :Dynamic):Void
	{
		//---*Si los datos del layer de tiles solidos no está almacenado:
		if (this.tilemapData == null)
		{	
			//loadTilemap(tileGraphic, layerName);
			this.tilemapData = Utils.loadTilemap(tileGraphic, Utils.SOLID_LAYER, this.mapElement);			
		}
		if (this.itemList == null)
		{
			this.itemList	= Utils.loadObjects(Utils.ITEM_LAYER, this.mapElement, "Pill");
		}
		
		//---*Carga el tileMap:
		this.loadMap(this.tilemapData, tileGraphic, tileWidth, tileHeight, 0, 1);
		//---*Carga los items:
		//Utils.loadObjects(loadObject, Utils.ITEM_LAYER, this.mapElement);
		//AddItems();
		
	}
		
	public	function AddItems():Void
	{
		
		var index: Int		=	0;
		var x: Float		=	0;
		var y: Float		=	0;
		var itemType: String;
		while (index < this.itemList.length)
		{
			x = Std.parseInt(this.itemList[index].att.x);
			y = Std.parseInt(this.itemList[index].att.y);
			itemType = this.itemList[index].att.type;
			//this.level.itemList.add(new Pill(x, y));
			this.level.addItem(x, y, itemType);
			index += 1;
		}
	}
	
	//---*Activa/Desactiva:
	public	function Activate(order:Bool):Void
	{
		this.active 	=	order;
		this.solid		=	order;
		this.visible	=	order;
	}
		
	
	override public function update()
	{
		super.update();
		//---*Solo es visible si se encuentra dentro de la Screen (con un poco de offset):
		this.visible = Utils.OnScreen(this.getScreenXY(_point, FlxG.camera),this.width,this.height,FlxG.camera,20,0);		
			
	}
	//---*Retorna un vecino o conexion al azar de la lista:
	public	function GetRandomConection():Int
	{		
		var index:Int = Std.random(this.conexiones.length);
		return this.conexiones[index];
	}
	
}